package com.funcablaze.tpxterm.window;

import com.funcablaze.tpxterm.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ResourceBundle;

public class AlertWindow extends Dialog<ButtonType> {
	
	private final String title;
	private final String message;
	private String copyText;
	
	public AlertWindow(@NotNull javafx.scene.control.Alert.AlertType alertType, @NotNull String title, @NotNull String message, @NotNull ResourceBundle bundle) {
		this.title = title;
		this.message = message;
		this.copyText = message; // 默认复制整个消息
		
		// 设置对话框属性
		setTitle(title);
		setHeaderText(null);
		setResizable(true);
		
		// 加载自定义FXML布局
		loadFXML(bundle);
		
		// 设置结果转换器
		setResultConverter(buttonType -> buttonType);
	}
	
	private void loadFXML(@NotNull ResourceBundle bundle) {
		try {
			Parent parent = Application.buildFXML("alert", bundle, null);
			// 获取FXML中的组件
			Label labelTitle = (Label) parent.lookup("#labelTitle");
			Label labelMessage = (Label) parent.lookup("#labelMessage");
			Button copyButton = (Button) parent.lookup("#buttonCopy");
			Button confirmButton = (Button) parent.lookup("#buttonConfirm");
			// 设置标题和消息
			labelTitle.setText(title);
			labelMessage.setText(message);
			// 添加按钮事件处理
			copyButton.setOnAction(event -> copyToClipboard());
			confirmButton.setOnAction(event -> setResult(ButtonType.OK));
			// 将自定义布局添加到对话框
			getDialogPane().setContent(parent);
			// 不允许调整大小
			getDialogPane().setPrefSize(400, 200);
		} catch (IOException e) {
			new javafx.scene.control.Alert(
					javafx.scene.control.Alert.AlertType.ERROR,
					"无法加载自定义警告对话框: " + e.getMessage()
			).show();
		}
	}
	
	// 设置复制内容（可选）
	public AlertWindow setCopyText(String copyText) {
		this.copyText = copyText;
		return this;
	}
	
	// 复制到剪贴板
	private void copyToClipboard() {
		Clipboard clipboard = Clipboard.getSystemClipboard();
		ClipboardContent content = new ClipboardContent();
		content.putString(copyText);
		clipboard.setContent(content);
	}
}
